using imitateMacQQ.WebApi.Configures;
using imitateMacQQ.WebApi.Domain.Request.utils;
using imitateMacQQ.WebApi.Repository.EFCore.Model;
using Microsoft.EntityFrameworkCore;

namespace imitateMacQQ.WebApi.Domain.utils;

public class UploadService : IUploadService
{
    public async Task<bool> UploadFile(IFormFileCollection files, string account, string path)
    {
        try
        {
            // var size = files.Sum(f => f.Length);
            var webRootPath = Path.Combine(Directory.GetCurrentDirectory(),
                "StaticFiles/") + account + "/" + path + "/";
            foreach (var formFile in files)
            {
                if (formFile.Length <= 0) continue;
                var fileExt = Guid.NewGuid() + "." + formFile.FileName.Split('.')[1];
                // var fileSize = formFile.Length;
                Directory.CreateDirectory(webRootPath);
                // File.Create(webRootPath);
                var filePath = webRootPath + fileExt;
                await using var stream = new FileStream(filePath, FileMode.Create);
                await formFile.CopyToAsync(stream);
                var res = await SaveSql(account, path,
                    account + "/" + path + "/" + fileExt);
                if (!res)
                    throw new Exception("SAVE SQL ERROR!");
            }

            return true;
        }
        catch (Exception ex)
        {
            _logHelper.LogError(ex);
            return false;
        }
    }

    public async Task<Request<string>> GetHeader(string account)
    {
        await using DataDbContext db = new();
        var usr = db.Users.FirstOrDefault(e => e.Account == account);
        return usr == null ? Request<string>.Ok("#") : Request<string>.Ok(usr.Header ?? "#");
    }

    public async Task<Request<string>> Get_Url(string account, string include)
    {
        try
        {
            switch (include)
            {
                case "background":
                {
                    var db = new DataDbContext();
                    var usr = await db.Backgrounds.FirstOrDefaultAsync(
                        e => e.Account == account);
                    return usr?.BackgroundUrl is null ? Request<string>.Ok("#", false, 
                            "Background Is Null") 
                        : Request<string>.Ok(usr.BackgroundUrl);
                }
                default:
                {
                    return Request<string>.Ok("#", false, "Bad Request");
                }
            }
        }
        catch (Exception ex)
        {
            _logHelper.LogError(ex);
            return Request<string>.Ok("#", false, "Bad Request");
        }
    }

    private readonly INLogHelper _logHelper;

    public UploadService(INLogHelper logHelper)
    {
        _logHelper = logHelper;
    }

    private async Task<bool> SaveSql(string account, string header, string path)
    {
        try
        {
            switch (header)
            {
                case "header":
                {
                    await using var db = new DataDbContext();
                    var usr = db.Users.FirstOrDefault(e => e.Account == account);
                    if (usr is null)
                        return false;
                    usr.Header = path;
                    await db.SaveChangesAsync();
                    return true;
                }
                case "background":
                {
                    await using var db = new DataDbContext();
                    var usr = db.Backgrounds.FirstOrDefault(e => e.Account == account);
                    if (usr is null)
                        db.Backgrounds.Add(new Background()
                        {
                            Account = account,
                            BackgroundUrl = path
                        });
                    else
                    {
                        usr.BackgroundUrl = path;
                    }

                    await db.SaveChangesAsync();
                    return true;
                }
                case "NULL":
                    throw new Exception("AWAIT ADMIN`S WANT");
            }
        }
        catch (Exception ex)
        {
            _logHelper.LogError(ex);
        }

        return false;
    }
}